﻿using DragonSolution.Web.Data.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Mvc;
using DragonSolution.Web.Common.Common;

namespace DragonSolution.Web.UI.DAL
{
    public class LoginBaseController : BaseController
    {
        private JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();

        /// <summary>
        /// 当前用户
        /// </summary>
        protected UserInfo CurrentUser
        {
            get
            {
                UserInfo user = null;
                if (Request.Cookies[ConstDim.CookieKeyUser] != null)
                {
                    string userJson = Request.Cookies[ConstDim.CookieKeyUser].Value;
                    user = jsonSerializer.Deserialize<UserInfo>(HttpUtility.UrlDecode(userJson));
                }
                return user;
            }
            private set
            {
                Response.Cookies[ConstDim.CookieKeyUser].Value = HttpUtility.UrlEncode(jsonSerializer.Serialize(value));
            }
        }
        protected void SetCurrentUser(UserInfo userInfo)
        {
            if (userInfo != null)
            {
                CurrentUser = userInfo;
            }
        }

        //验证登陆
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            try
            {
                bool result = false;
                //当前url
                //string currentUrl = HttpUtility.UrlEncode(Request.Url.ToString());

                //检测控制器上是否有特性CheckLoginAttribute，以及特性的_isNeedLogin值
                var controllerAttrs = filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(CheckLoginAttribute), false);
                if (controllerAttrs.Count() > 0)
                {
                    var controAttr = controllerAttrs[0] as CheckLoginAttribute;
                    if (controAttr != null)
                    {
                        result = controAttr._isNeedLogin;
                    }
                }
                //检测action上是否有特性CheckLoginAttribute，以及特性的_isNeedLogin值
                var actionAttrs = filterContext.ActionDescriptor.GetCustomAttributes(typeof(CheckLoginAttribute), false);
                if (actionAttrs.Count() > 0)
                {
                    var attr = actionAttrs[0] as CheckLoginAttribute;
                    if (attr != null)
                    {
                        result = attr._isNeedLogin;
                    }
                }

                //验证是否登陆
                if (CurrentUser == null && result)
                {
                    //filterContext.Result = new RedirectResult("/Account/Login?ReturnURL=" + currentUrl);
                    filterContext.Result = new RedirectResult("/Account/Login");
                }
            }
            catch (Exception e) { }

        }
    }
}